﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using Maticsoft.Common;
using System.Drawing;
using LTP.Accounts.Bus;
namespace dzs.Web.inventory
{
    public partial class List : Web.Admin.BasePage
    {
        dzs.BLL.inventory bll = new dzs.BLL.inventory();
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                dzs.BLL.storeinfo bst = new BLL.storeinfo();
                ddlstore.DataSource = bst.GetddlList(" uid="+getid());
                ddlstore.DataTextField = "sname";
                ddlstore.DataValueField = "sid";
                ddlstore.DataBind();
                ddlstore.Items.Insert(0, new ListItem("所有", "0"));
                BindData();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            string idlist = GetSelIDlist();
            if (idlist.Trim().Length == 0)
                return;
            bll.DeleteList(idlist);
            BindData();
        }

        #region gridView

        public DataSet BindData()
        {
            #region
            //if (!Context.User.Identity.IsAuthenticated)
            //{
            //    return;
            //}
            //AccountsPrincipal user = new AccountsPrincipal(Context.User.Identity.Name);
            //if (user.HasPermissionID(PermId_Modify))
            //{
            //    gridView.Columns[6].Visible = true;
            //}
            //if (user.HasPermissionID(PermId_Delete))
            //{
            //    gridView.Columns[7].Visible = true;
            //}
            #endregion



            DataSet ds = GetDataPage();
                gridView.DataSource = ds;
                gridView.DataBind();
                return ds;
            
        }

        private DataSet GetDataPage()
        {

            DataSet ds = new DataSet();
            StringBuilder strWhere = new StringBuilder();
            strWhere.Append(" and nums>0 ");
            if (ddlstore.SelectedValue != "0")
            {
                strWhere.AppendFormat(" and sid={0} ", ddlstore.SelectedValue);
            }
            if (txtname.Text != "")
            {
                strWhere.AppendFormat(" and spname like '%{0}%' ", txtname.Text);

            }
            if (Session["login"] != null)
            {
                DataSet u = (DataSet)Session["login"];

                if (u.Tables[0].Rows[0]["roles_id"].ToString() == "2")
                {
                    strWhere.AppendFormat(" and uid={0}", u.Tables[0].Rows[0]["user_id"]);
                }
            }
            ds = bll.GetinventoryListByPage(strWhere.ToString(), "", (this.AspNetPager1.CurrentPageIndex - 1) * this.AspNetPager1.PageSize + 1, this.AspNetPager1.CurrentPageIndex * this.AspNetPager1.PageSize);

            this.AspNetPager1.RecordCount = bll.GetinventoryRecordCount(strWhere.ToString());
            
            return ds;
        }


        private DataSet GetData()
        {

            DataSet ds = new DataSet();
            StringBuilder strWhere = new StringBuilder();
            strWhere.Append(" and nums>0 ");
            if (ddlstore.SelectedValue != "0")
            {
                strWhere.AppendFormat(" and sid={0} ", ddlstore.SelectedValue);
            }
            if (txtname.Text != "")
            {
                strWhere.AppendFormat(" and spname like '%{0}%' ", txtname.Text);

            }
            if (Session["login"] != null)
            {
                DataSet u = (DataSet)Session["login"];

                if (u.Tables[0].Rows[0]["roles_id"].ToString() == "2")
                {
                    strWhere.AppendFormat(" and uid={0}", u.Tables[0].Rows[0]["user_id"]);
                }
            }
            ds = bll.Getinventory(strWhere.ToString());
            return ds;
        }

        protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridView.PageIndex = e.NewPageIndex;
            BindData();
        }
        protected void gridView_OnRowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                //e.Row.Cells[0].Text = "<input id='Checkbox2' type='checkbox' onclick='CheckAll()'/><label></label>";
            }
        }
        protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            e.Row.Attributes.Add("style", "background:#FFF");
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindData();
        }

        protected void gridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //#warning 代码生成警告：请检查确认真实主键的名称和类型是否正确
            //int ID = (int)gridView.DataKeys[e.RowIndex].Value;
            //bll.Delete(ID);
            //gridView.OnBind();
        }

        private string GetSelIDlist()
        {
            string idlist = "";
            bool BxsChkd = false;
            for (int i = 0; i < gridView.Rows.Count; i++)
            {
                CheckBox ChkBxItem = (CheckBox)gridView.Rows[i].FindControl("DeleteThis");
                if (ChkBxItem != null && ChkBxItem.Checked)
                {
                    BxsChkd = true;
                    //#warning 代码生成警告：请检查确认Cells的列索引是否正确
                    if (gridView.DataKeys[i].Value != null)
                    {
                        idlist += gridView.DataKeys[i].Value.ToString() + ",";
                    }
                }
            }
            if (BxsChkd)
            {
                idlist = idlist.Substring(0, idlist.LastIndexOf(","));
            }
            return idlist;
        }

        #endregion

        protected void btnout_Click(object sender, EventArgs e)
        {
            //DataSet ds = BindData();
            //string f = DateTime.Now.Ticks.ToString();
            //CreateExcel(ds,f+ ".xls");

            DataSet ds = GetData();
            gridView.DataSource = ds;

            gridView.AllowPaging = false;
            //gridView.Columns[0].Visible = false;
            gridView.DataBind();
            string f = DateTime.Now.Ticks.ToString();
            ExportExcel(gridView, f);
            gridView.DataSource = ds;
            gridView.AllowPaging = true;
            //gridView.Columns[0].Visible = true;
            gridView.DataBind();
           

        }
        public override void VerifyRenderingInServerForm(Control control)
        {
            //这里没有内容。
        }

        public void ExportExcel(System.Web.UI.WebControls.WebControl objControl, string strFileName)
        {

            strFileName = System.Web.HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8);
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.Buffer = true;
            System.Web.HttpContext.Current.Response.Charset = "gb2312";
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "online; filename=" + strFileName + ".xls");
            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";

            System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("zh-CN", true);
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

            objControl.RenderControl(oHtmlTextWriter);

            objControl = null;
            System.Web.HttpContext.Current.Response.Write(oStringWriter.ToString().Replace("<td", "<td STYLE='MSO-NUMBER-FORMAT:\\@'"));
            System.Web.HttpContext.Current.Response.Buffer = false;
            System.Web.HttpContext.Current.Response.End();
        }
        public void CreateExcel(DataSet ds, string FileName)
        {
            HttpResponse resp;
            resp = Page.Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
            string colHeaders = "", ls_item = "";
            int i = 0;

            //定义表对象与行对像，同时用DataSet对其值进行初始化 
            DataTable dt = ds.Tables[0];
            DataRow[] myRow = dt.Select("");
            // typeid=="1"时导出为EXCEL格式文件；typeid=="2"时导出为XML格式文件 

            //取得数据表各列标题，各标题之间以\t分割，最后一个列标题后加回车符 
            colHeaders += "仓位" + "\t";
            colHeaders += "仓位类型" + "\t";
            colHeaders += "仓库" + "\t";
            colHeaders += "数量" + "\t";
            colHeaders += "项目编号" + "\t";
            colHeaders += "需用单位" + "\t";
            colHeaders += "项目名称" + "\t";
            colHeaders += "项目类型" + "\t";
            colHeaders += "sid" + "\t";
            colHeaders += "仓位状态" + "\t";
            colHeaders += "mid" + "\t";
            colHeaders += "单位" + "\t";
            colHeaders += "供应商" + "\t";
            colHeaders += "物料描述" + "\n";
            //colHeaders += "规格型号" + "\t";
            //colHeaders += "需用单位" + "\t";        
            //colHeaders += "项目类型" + "\n";
            //向HTTP输出流中写入取得的数据信息 
            resp.Write(colHeaders);
            //逐行处理数据   
            foreach (DataRow row in myRow)
            {
                //在当前行中，逐列获得数据，数据之间以\t分割，结束时加回车符\n 
                for (i = 0; i < dt.Columns.Count - 1; i++)
                    ls_item += row[i].ToString() + "\t";
                ls_item += row[i].ToString() + "\n";
                //当前行数据写入HTTP输出流，并且置空ls_item以便下行数据     
                resp.Write(ls_item);
                ls_item = "";
            }


            //写缓冲区中的数据到HTTP头文件中 
            resp.End();


        }




    }
}
